package group.rober.jeki.controller;

import group.rober.jeki.entity.Article;
import group.rober.jeki.entity.Domain;
import group.rober.jeki.entity.Tag;
import group.rober.jeki.exception.JekiException;
import group.rober.jeki.service.ArticleService;
import group.rober.jeki.service.CommentService;
import group.rober.jeki.service.DomainService;
import group.rober.jeki.service.TagService;
import group.rober.runtime.holder.WebHolder;
import group.rober.runtime.kit.MapKit;
import group.rober.runtime.kit.ValidateKit;
import group.rober.runtime.lang.MapData;
import group.rober.runtime.model.PaginationData;
import group.rober.search.entity.SearchResult;
import group.rober.search.service.SearchService;
import io.swagger.annotations.Api;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryparser.classic.ParseException;
import org.apache.lucene.search.Sort;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(description = "主页面")
@Controller
public class IndexController {

    @Autowired
    DomainService domainService;
    @Autowired
    ArticleService articleService;
    @Autowired
    CommentService commentService;
    @Autowired
    TagService tagService;
    @Autowired
    SearchService searchService;

    private int portalSize = 7;
    private int defaultPageSize = 6;

    @RequestMapping("/")
    public ModelAndView index() {

        Map<String,Object> vars = new HashMap<String,Object>();
        vars.put("stickedArticleList",articleService.getStickedArticleList());          //推荐文章
        vars.put("recentArticleList",articleService.getRecentArticleList(0,portalSize));  //最新文章
        vars.put("tweetList",commentService.getTweetList());                            //动弹

        //[取标准文章]信息块
        List<Tag> officalDocTagList = getDomainTags("official-document");
        PaginationData officalDocArticle = articleService.getArticleListByDomain("official-document",0,portalSize);
        vars.put("officalDocTagList",officalDocTagList);                                //[标准文档]标签列表
        vars.put("officalDocArticleList",officalDocArticle.getDataList());                        //[标准文档]文章列表

        //[常见问题]信息块
        List<Tag> faqTagList = getDomainTags("faq");
        PaginationData faqArticle = articleService.getArticleListByDomain("faq",0,portalSize);        //[常见问题]信息块
        vars.put("faqTagList",faqTagList);                                //[常见问题]标签列表
        vars.put("faqArticleList",faqArticle.getDataList());                        //[常见问题]文章列表

        //[问答交流]
        List<Tag> snsTagList = getDomainTags("synthesize");
        PaginationData snsArticle = articleService.getArticleListByDomain("synthesize",0,portalSize);
        vars.put("snsTagList",snsTagList);                                //[问答交流]标签列表
        vars.put("snsArticleList",snsArticle.getDataList());                        //[问答交流]文章列表

        //[业务方案]
        List<Tag> bzsoTagList = getDomainTags("business-solution");
        PaginationData bzsoArticle = articleService.getArticleListByDomain("business-solution",0,portalSize);
        vars.put("bzsoTagList",bzsoTagList);
        vars.put("bzsoArticleList",bzsoArticle.getDataList());
        //所有标签
        vars.put("allTagList",tagService.getTagList());

        //[JAVA]
        List<Tag> javaTagList = getDomainTags("java");
        PaginationData javaArticle = articleService.getArticleListByDomain("java",0,portalSize);
        vars.put("javaTagList",javaTagList);
        vars.put("javaArticleList",javaArticle.getDataList());

        //[数据库]
        List<Tag> dbTagList = getDomainTags("database");
        PaginationData dbArticle = articleService.getArticleListByDomain("database",0,portalSize);
        vars.put("dbTagList",dbTagList);
        vars.put("dbArticleList",dbArticle.getDataList());

        return new ModelAndView("views/index",vars);
    }

    protected List<Tag> getDomainTags(String domainCode){
        Domain domain = domainService.getDomainByCode(domainCode);
        return domainService.getInDomainTagList(domain.getId(),3);
    }

    @GetMapping("/searching")
    @ResponseBody
    public MapData searchingArticle(@RequestParam("keyWord") String keyWord, @RequestParam("page") int page, @RequestParam("size") int size){
//        Sort sort=new Sort(new SortField[]{new SortField("viewCount",SortField.Type.STRING),new SortField("updatedTime",SortField.Type.STRING)});
        Sort sort=new Sort();
        MapData ret = new MapData();
        try {
            int pageIndex  = page;
            int pageSize  = size;
            SearchResult result = searchService.searchDocument(new String[]{"title","summary","content"},keyWord,sort,pageIndex,pageSize);
            ret.put("hitsCount",result.getHitsCount());
            List<MapData> artciles = new ArrayList<MapData>();
            for(Document document : result.getDataList()){
                MapData articleObject = new MapData();

                articleObject.put("id",document.get("id"));
                articleObject.put("type",document.get("type"));
                articleObject.put("title",document.get("title"));
                articleObject.put("summary",document.get("summary"));
                articleObject.put("content",document.get("content"));
                articleObject.put("updatedTime",document.get("updatedTime"));
                articleObject.put("viewCount",document.get("viewCount"));
                articleObject.put("hlTitle",document.get("hlTitle"));
                articleObject.put("hlSummary",document.get("hlSummary"));
                articleObject.put("hlContent",document.get("hlContent"));

                artciles.add(articleObject);
            }
            ret.put("artciles",artciles);
            return ret;
        } catch (ParseException e) {
            throw new JekiException("",e);
        } catch (IOException e) {
            throw new JekiException("",e);
        }

    }

    @RequestMapping(path = "/search",method = {RequestMethod.GET,RequestMethod.POST})
    public ModelAndView search(@RequestParam("keyWord") String keyWord, @RequestParam("page") int page, @RequestParam("size") int size){
        MapData ret = searchingArticle(keyWord,page,size);
        ret.put("keyWord",keyWord);
        return new ModelAndView("views/search",ret);
    }

    @RequestMapping(value={"/domain/{domainCode}"})
    public ModelAndView domain(@PathVariable("domainCode") String domainCode,Map<String, Object> vars) {
        if(vars==null)vars = new HashMap<String,Object>();
        PaginationData pdArticle = null;

        //取当前页页码，取页面大小，如果没有传，则使用默认值
//        Integer pageIndex = WebHolder.getRequestMapData().getValue("pageIndex").intValue(0);
//        Integer pageSize = WebHolder.getRequestParameter("pageSize").intValue(10);
        Integer pageIndex = WebHolder.getRequestParameterForInt("pageIndex",0);
        Integer pageSize = WebHolder.getRequestParameterForInt("pageSize",defaultPageSize);

        Tag tag = (Tag)vars.get("activeTag");
        if(tag==null){
            tag = new Tag();
            vars.put("activeTag",tag);
        }else{
            pdArticle = articleService.getArticleListByTag(tag.getCode(),pageIndex,pageSize);
        }

        Domain domain = domainService.getDomainByCode(domainCode);
        ValidateKit.isNotExist(domain,"领域{0}不存在",domainCode);

        if(pdArticle==null){
            pdArticle = articleService.getArticleListByDomain(domainCode,pageIndex,pageSize);
        }
        List<Tag> tagList = domainService.getInDomainTagList(domain.getId());
        vars.put("tagList",tagList);
        vars.put("articleList",pdArticle.getDataList());
        vars.put("paginationArticle",pdArticle);

        vars.put("activeDomain",domain);

        return new ModelAndView("views/domain",vars);
    }

    @RequestMapping("/domain-tag/{domainCode}/{tagCode}")
    public ModelAndView domainTag(@PathVariable("domainCode") String domainCode,@PathVariable("tagCode") String tagCode) {
        Map<String,Object> vars = new HashMap<String,Object>();

        Tag tag = tagService.getTagByCode(tagCode);
        vars.put("activeTag",tag);
        return domain(domainCode,vars);
    }

    @RequestMapping("/tag/{tagCode}")
    public ModelAndView tag(@PathVariable("tagCode") String tagCode) {
        Map<String,Object> vars = new HashMap<String,Object>();

        Tag tag = tagService.getTagByCode(tagCode);
        ValidateKit.isNotExist(tag,"标签{0}不存在",tagCode);

        PaginationData articlePaginData = articleService.getArticleListByTag(tag.getCode(),0,10);

        vars.put("activeTag",tag);
        vars.put("articleList",articlePaginData.getDataList());
        return new ModelAndView("views/tag",vars);
    }

    @RequestMapping("/register")
    public ModelAndView register() {
        return new ModelAndView("views/register");
    }

    @RequestMapping("/logon")
    public String logon() {
        return "views/logon";
    }
    @RequestMapping("/logoff")
    public ModelAndView logoff() {
        return index();
    }
    @RequestMapping("/logonAction")
    public ModelAndView logonAction() {
        return new ModelAndView("views/logon");
    }

    @RequestMapping("/markdown-guide")
    public ModelAndView markdownGuide() {
        Map<String,Object> vars = MapKit.newHashMap();
        return new ModelAndView("views/markdown-guide",vars);
    }

}
